package com.btkjgc.service.impl;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.Dictionary;
import com.btkjgc.models.ExceptionRecord;
import com.btkjgc.models.extend.BatteryModel;
import com.btkjgc.models.extend.ExceptionRecordModel;
import com.btkjgc.models.extend.ExchangeElectricRecordModel;
import com.btkjgc.service.intf.ElectricChargingRecordManageService_Intf;
import com.btkjgc.utils.DateUtils;
import com.btkjgc.utils.ExcelExportor;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.utils.LogUtils;

/**
 * Created by _ESE on 2015/2/9.
 */
@Component
public class ElectricChargingRecordManageService_Impl extends BaseService_Impl
		implements ElectricChargingRecordManageService_Intf {

	static Logger logger = Logger.getLogger(ElectricChargingRecordManageService_Impl.class);

 
	@Override
	public void setListData(HttpServletRequest request, ModelAndView mv,
			int pageIndex, int totalRecord,
			List<ExchangeElectricRecordModel> exchangeElectricRecordModelList) {
		// TODO Auto-generated method stub

		AdminUser adminUser = (AdminUser) request.getSession().getAttribute(
				"user");

		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
	 
		mv.addObject("user_info", adminUser);
		mv.addObject("exchange_electric_record_list", exchangeElectricRecordModelList);

		String sql = " select aut.name value,concat(aut.id,'') 'key'  from account_user_t aut where aut.del = 0  and aut.type=1";

		List<Dictionary> companyList = HibernateUtil.executeSQLQueryList(sql,
				Dictionary.class);
		if (companyList.size() > 0) {
			mv.addObject("companyList", companyList);
		}

	    sql = " select ct.name value,concat(ct.id,'') 'key'  from cartype_t ct where ct.del = 0 ";

		List<Dictionary> cartypeList = HibernateUtil.executeSQLQueryList(sql,
				Dictionary.class);
		if (companyList.size() > 0) {
			mv.addObject("cartypeList", cartypeList);
		}
		
	    sql = " select ecst.name value,concat(ecst.id,'') 'key'  from electric_charging_site_t ecst where ecst.del = 0 ";

		List<Dictionary> siteList = HibernateUtil.executeSQLQueryList(sql,
				Dictionary.class);
		if (companyList.size() > 0) {
			mv.addObject("siteList", siteList);
		}

		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
	}


	@Override
	public void setBatteryListData(HttpServletRequest request, ModelAndView mv,
			int pageIndex, int totalRecord,
			List<BatteryModel> batteryModelList) {
		// TODO Auto-generated method stub
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		
		
		mv.addObject("battery_list", batteryModelList);
		
		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
	 
		
	}

	@Override
	public void doDownloadAction(HttpServletRequest request,
			HttpServletResponse response, String sql) {
		// TODO Auto-generated method stub
		ExcelExportor<String[]> exproter = new ExcelExportor<String[]>();
		try{
			response.setHeader("content-disposition", "attachment;filename="
					+ URLEncoder.encode(DateUtils.getDateTime("yyyyMMdd")+"换电记录列表.xls", "UTF-8"));
			OutputStream out = response.getOutputStream();
			
			List<ExchangeElectricRecordModel> items = HibernateUtil.executeSQLQueryList(sql, ExchangeElectricRecordModel.class);
			
			List<String[]> rows = new ArrayList<String[]>();
			
			String[] header =  new String[] { "订单流水号", "时间", "车辆", "费用/余额", "对公余额",
					"司机账号ID", "所属公司", "SOC", "行驶/总里程", "应收计费里程", "TBOX里程", "优惠券使用",
					"网点", "备注", "状态"};
			
			for(ExchangeElectricRecordModel item : items)
			{
				String[] row = new String[header.length];
				row[0] = item.getSerialNum();
				row[1] = String.valueOf(item.getCreatedate());
				
				row[2] = item.getCarbrand();
				row[3] = String.valueOf(item.getFare()/100)+"/"+String.valueOf(item.getAfter_consum_balance()/100);
				row[4] = String.valueOf(item.getCompany_available_balance()/100);
				
				row[5] = item.getDriverId();
				row[6] = item.getCompanyname();
				row[7] = String.valueOf(item.getSoc())+"%";
				
				row[8] = String.valueOf(item.getTravelMileage())+"/"+String.valueOf(item.getTbox());
				row[9] = String.valueOf(item.getFare()/item.getUnitprice());
				row[10] = String.valueOf(item.getTbox());
				
				row[11] = "0";
				row[12] = item.getSitename();
				row[13] = item.getComment();
				
				row[14] = item.getStatusName();
				rows.add(row);
			}
			exproter.exportExcel(DateUtils.getDateTime("yyyyMMdd")+"换电记录列表", header, rows, out, null);
			
		}catch(Exception e){
			LogUtils.error(e);
		}
	}


	@Override
	public ExceptionRecordModel getPersonByExchageid(String id) {
		// TODO Auto-generated method stub
		
		String sql="SELECT\n" +
				"	ait.available_balance balance,\n" +
				"	aut. NAME accountName,\n" +
				"	aut.account,\n" +
				"	aut.id accountid,\n" +
				"   eert.fare\n" +
				"FROM\n" +
				"	exchange_electric_record_t eert\n" +
				"LEFT JOIN car_account_log_t cat ON cat.id = eert.carAccountid\n" +
				"LEFT JOIN account_user_t aut ON aut.id = cat.accountid\n" +
				"LEFT JOIN account_info_t ait ON ait.accountid = aut.id\n" +
				"where eert.id='"+id+"'";
		
		ExceptionRecordModel exceptionRecordModel=(ExceptionRecordModel) HibernateUtil.executeSQLQueryObject(sql, ExceptionRecordModel.class);
		
		return exceptionRecordModel;
	}


	@Override
	public AjaxObj getRecordByExchageid(String id) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		Integer sum = 0;
		
		try{
			String faresql = " select fare from exchange_electric_record_t where id="+id;
			Integer fare = HibernateUtil.executeSQLQueryInt(faresql);
			String sql = " select * from exception_record_t where execChargid="+id+" and del=0";
			List<ExceptionRecordModel> exceptionRecordModelList = HibernateUtil.executeSQLQueryList(sql, ExceptionRecordModel.class);
			if(exceptionRecordModelList!=null&&!exceptionRecordModelList.equals("")){
				for(int i = 0;i < exceptionRecordModelList.size();i++){
					sum+=exceptionRecordModelList.get(i).getAmount();
				}
			}
			if(sum>=fare){
				ajaxObj.setResult(false);
				ajaxObj.setMsg("该条换电记录已退完款！");
			}else{
				ajaxObj.setVariable(fare-sum);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return ajaxObj;
	}


	@Override
	public AjaxObj insertRefundRecord(ExceptionRecordModel exceptionRecordModel) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		ExceptionRecord  exceptionRecord = new ExceptionRecord();

		try {
			PropertyUtils.copyProperties(exceptionRecord,
					exceptionRecordModel);
			exceptionRecord.setDel(0);
			exceptionRecord.setCreatedate(new Date());
			exceptionRecord.setOperid(getLoginUser().getId());
			exceptionRecord.setOperdate(new Date());
			HibernateUtil.save(exceptionRecord);

		} catch (Exception e) {
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("添加时出错");
		}
		return ajaxObj;
	}
	 
}
